package com.servlet;

import com.dao.impl.AdminDaoImpl;
import com.entity.Users;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;

import static com.util.Constant.*;

@WebServlet(name = "HomeAdminLoginServlet",value = "/home")
public class HomeAdminLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/admin.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        String username = (String) session.getAttribute("username");
        if (Objects.nonNull(username)) { // 表示用户已经登录，username已经存在session对象中
            try {
                Users user = new AdminDaoImpl().login(username, "password");
                if (Objects.nonNull(user)) {
                    req.setAttribute("user", user);
                    req.getRequestDispatcher("/admin/index.jsp").forward(req, resp);
                } else {
                    req.getRequestDispatcher("/adminLogin").forward(req, resp);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else { // username不在session对象
            Cookie[] cookies = req.getCookies();
            if (Objects.nonNull(cookies)) {
                Optional<Cookie> remeberMeCookie = Arrays.stream(cookies)
                        .filter(cookie -> cookie.getName().equals(REMEMBER))
                        .findFirst(); // 找到7天免登录的cookie
                remeberMeCookie.ifPresent(cookie -> {
                    String usernameValue = cookie.getValue();
                    try {
                        Users user = new AdminDaoImpl().login(username, "password");
                        if (Objects.nonNull(user)) {
                            req.getSession().setAttribute("username", usernameValue);
                            req.setAttribute("user", user);
                            req.getRequestDispatcher("/user.jsp").forward(req, resp);
                        } else {
                            req.getRequestDispatcher("/adminLogin").forward(req, resp);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
            }
            req.getRequestDispatcher("/adminLogin").forward(req, resp);
        }
    }
}
